package com.ticketbooking.service.impl;

import com.ticketbooking.entity.UserEntity;
import com.ticketbooking.service.IUserDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Types;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserDaoImpl implements IUserDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserEntity find(String userName, String userPwd) {
        String sql = "select * from user u where u.userName = ? or u.password = ?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[]{userName,userPwd},new int[]{Types.VARCHAR,Types.VARCHAR});
        return getUser(list);
    }

    @Override
    public void add(UserEntity user) {
        String sql = "insert into user(id,username,password) values (?,?,?)";
        Object args[] = {user.getId(),user.getUserName(),user.getPassword()};
        int[] argTypes = {Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
        jdbcTemplate.update(sql,args,argTypes);
    }

    @Override
    public UserEntity find(String id) {
        String sql = "select * from user u where u.id = ?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[]{id},new int[]{Types.VARCHAR});
        return getUser(list);
    }

    private UserEntity getUser(List<Map<String, Object>> userList){
        UserEntity user = new UserEntity();
        if(userList.size()>0){
            Map<String, Object> map = userList.get(0);
            user.setId((String)map.get("id"));
            user.setUserName((String)map.get("username"));
            user.setPassword((String)map.get("password"));
        }
        return user;
    }
}
